import React, { useEffect, useRef, useState } from 'react'
import {
  Row,
  Col,
  Table,
} from 'antd'
import * as echarts from 'echarts/core'
import { TitleComponent, TooltipComponent, GridComponent } from 'echarts/components'
import { BarChart, LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { io } from 'socket.io-client'

import { getStatistics } from '../../api/statistics'

echarts.use([TitleComponent, TooltipComponent, GridComponent, BarChart, LineChart, UniversalTransition, CanvasRenderer])

export default function Dashboard() {

  // 保存统计数据
  const [statistic, setStatistic] = useState({})
  const [realtime, setRealtime] = useState([])

  // 预约挂号图表
  const registrationRef = useRef()
  // 充值图表
  const depositRef = useRef()

  useEffect(async() => {
    const result = await getStatistics()
    setStatistic(result)
    console.log(result)
  }, [])

  // 预约挂号图表绘制
  useEffect(() => {
    // 创建 ECharts 实例
    const myChart = echarts.init(registrationRef.current)
    // 创建选项对象
    const option = {
      title: {
        text: '近7日预约挂号情况',
      },
      xAxis: {
        type: 'category',
        data: statistic.registration?.map(reg => reg.date),
        name: '日期',
        nameLocation: 'start',
        nameTextStyle: {
          padding: 8,
        },
      },
      yAxis: {
        type: 'value',
        name: '预约人次',
      },
      tooltip: {
        show: true,
      },
      series: [
        {
          data: statistic.registration?.map(reg => reg.value),
          type: 'bar',
        },
      ],
    }
    // 调用 setOption()
    option && myChart.setOption(option)

    return () => {
      myChart.dispose()
    }
  }, [statistic.registration])

  // 绘制门诊充值图表
  useEffect(() => {
    const myChart = echarts.init(depositRef.current)
    const option = {
      title: {
        text: '近7日门诊充值趋势',
      },
      xAxis: {
        type: 'category',
        data: statistic.deposits?.map(dep => dep.date),
        name: '日期',
      },
      yAxis: {
        type: 'value',
        value: '单位（元）',
      },
      tooltip: {
        show: true,
      },
      series: [
        {
          data: statistic.deposits?.map(dep => dep.value),
          type: 'line',
          smooth: true,
        },
      ],
    }

    option && myChart.setOption(option)

    return () => {
      myChart.dispose()
    }
  }, [statistic.deposits])

  // 建立服务器 socket 的连接，通信
  useEffect(() => {
    // 建立与服务器的连接
    const socket = io(process.env.REACT_APP_HTTP)
    // 注册用于接收服务器数据的事件
    socket.on('onmessage', message => {
      console.log('接收到消息：', message)
      setRealtime(JSON.parse(message).patients)
    })

    return () => {
      // 要在组件销毁之前关闭 socket 连接
      socket.close()
    }
  }, [])

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
  ]

  return (
    <div>
      Dashboard-首页
      <Row>
        <Col span={12}>
          <div ref={registrationRef} style={{width: 480, height: 300}}></div>
        </Col>
        <Col span={12}>
          <div ref={depositRef} style={{width: 480, height: 300}}></div>
        </Col>
      </Row>

      <Row>
        <Col span={12}>
          <Table rowKey="id" columns={columns} dataSource={realtime} pagination={false} />
        </Col>
      </Row>
    </div>
  )
}

